
package com.mengmeizi;

import com.android.update.ADViewFliperLayout;
import com.mengmeizi.adapter.MainImagesAdapter;
import com.mengmeizi.bean.ImageDataBean;
import com.mengmeizi.db.DBHelper;
import com.mengmeizi.db.ImageBufferDB;
import com.mengmeizi.interfaces.JsonInflater;
import com.mengmeizi.net.Method;
import com.mengmeizi.services.UpgradeService;
import com.mengmeizi.threads.URLDataThread;
import com.mengmeizi.util.Const;
import com.mengmeizi.util.CustomDialog;
import com.mengmeizi.util.DialogUtil;
import com.mengmeizi.util.ImageManager;
import com.mengmeizi.util.LogOut;
import com.mengmeizi.util.Tools;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActZhengdian extends Activity implements Callback, JsonInflater, OnClickListener, OnScrollListener,
        OnItemClickListener {

    private SoftApplication application;

    private Handler handler;

    private Button btnManager, btnMore;

    private ArrayList<ImageDataBean> imageUrls;

    private CustomDialog quitDialog;

    private static final String SHORTCUT_NOASK = "noask";

    private static final String SHORTCUT_AGREE = "agree";

    private Map<String, String> params;

    private boolean lastPage;

    private URLDataThread thread;

    private GridView grvThumbs;

    private MainImagesAdapter adapter;

    private int page, totalPage;

    private SharedPreferences preSetting;

    private ImageView imvMainDesc;

    private boolean lock = false;

    private RelativeLayout rllLoading;

    private String upgradeUrl;

    private CustomDialog upgradeDialog;

    private boolean check;

    private ImageView imvArrow;

    private Animation shake;

    private int bufferedPage;

    private SharedPreferences spre;

    private DBHelper helper;

    private TextView txvPageInfo;

    private EditText edtInputPage;

    private Button btnSkip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_main);

        MobclickAgent.updateOnlineConfig(this);
        // MobclickAgent.setDebugMode(true);

        application = (SoftApplication) getApplication();
        application.addActivity(this);
        // 存储ad页面
        if (application.getAdLayout() == null) {
            ADViewFliperLayout adLayout = new ADViewFliperLayout(this);
            application.storeAdLayout(adLayout);
        }

        Tools.setDensityValue(this);

        handler = new Handler(this);

        spre = getSharedPreferences(Const.SHARED_PREFERENCES_MESSAGE, Context.MODE_PRIVATE);
        helper = new DBHelper(this, ImageBufferDB.TABLE);

        initView();
        createShortcut();
        // 检查更新版本
        URLDataThread thread = new URLDataThread(this, this, Const.URL_UPGRADE, null, null, Method.GET,
                Const.ACT_UPGRADE);
        thread.start();
    }

    /***
     * 下载图片列表数据
     * 
     * @param page
     */
    private void LoadDataFromNet(int page) {
        txvPageInfo.setText(getString(R.string.pageInfo, page, 1));
        handler.sendEmptyMessage(Const.DIALOG_SHOW);
        if (params == null) {
            params = new HashMap<String, String>();
        }
        params.clear();
        params.put("page", String.valueOf(page));
        thread = new URLDataThread(this, this, Const.URL_GET_DATA, params, null, Method.GET, Const.ACT$GETIMAGEDATA);
        thread.start();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Const.DIALOG_QUIT_BUTTON:
                DialogUtil.dismissDialog(quitDialog);
                application.exit();
                break;
            case Const.DIALOG_CANCEL_BUTTON:
                if (quitDialog != null) {
                    DialogUtil.dismissDialog(quitDialog);
                }
                break;
            case Const.DIALOG_SHOW:
                rllLoading.setVisibility(View.VISIBLE);
                break;
            case Const.DIALOG_DISMISS:
                rllLoading.setVisibility(View.GONE);
                break;
            case Const.ACT$GETIMAGEDATA_SUCESS:
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                imvArrow.setVisibility(View.VISIBLE);
                imvArrow.clearAnimation();
                imvArrow.startAnimation(shake);
                adapter.notifyDataSetChanged();
                break;
            case Const.ACT_UPGRADE:
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                upgradeUrl = (String) msg.obj;
                Tools.showNotification(ActZhengdian.this, getString(R.string.upgradeTitle),
                        getString(R.string.upgradeMessage), upgradeUrl);
                upgradeDialog = DialogUtil.showAlertDialog(ActZhengdian.this, handler,
                        getString(R.string.upgradeTitle), getString(R.string.upgradeMessageButton), Const.ACT_CONFIRM,
                        Const.ACT_CANCEL);
                break;
            case Const.ACT_CONFIRM:
                Intent intent = new Intent(this, UpgradeService.class);
                intent.putExtra("downUrl", upgradeUrl);
                ActZhengdian.this.startService(intent);
                DialogUtil.dismissDialog(upgradeDialog);
                break;
            case Const.ACT_CANCEL:
                DialogUtil.dismissDialog(upgradeDialog);
                break;
            case Const.CHECK_NETWORK:
                if (!check && !Tools.hasNetwork(this)) { // 网络正常
                    check = true;
                    bufferedPage = Integer.parseInt(spre.getString(Const.SHARED_BUFFEREDPAGE, "1"));
                    helper.openReadableDatabase();
                    Cursor cursor = helper.getDatas(ImageBufferDB.sql$selectAll());
                    ImageDataBean tmpBean = null;
                    while (cursor.moveToNext()) {
                        tmpBean = new ImageDataBean();
                        tmpBean.imageUrl = cursor.getString(cursor.getColumnIndex(ImageBufferDB.IMAGE));
                        tmpBean.thumbUrl = cursor.getString(cursor.getColumnIndex(ImageBufferDB.THUMBS));
                        imageUrls.add(tmpBean);
                    }
                    helper.close();
                    handler.sendEmptyMessage(Const.ACT$GETIMAGEDATA_SUCESS);
                }
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                Tools.showShortToast(this, getString(R.string.checkNetwork));
                break;
            case Const.SHOW_TOAST:
                Tools.showShortToast(this, (String) msg.obj);
                break;
            default:
                break;
        }
        return false;
    }

    private void initView() {
        btnManager = (Button) findViewById(R.id.btnManager);
        btnMore = (Button) findViewById(R.id.btnMore);
        btnManager.setOnClickListener(this);
        btnMore.setOnClickListener(this);

        txvPageInfo = (TextView) findViewById(R.id.txvPageInfo);
        edtInputPage = (EditText) findViewById(R.id.edtInputPage);
        txvPageInfo.setText(getResources().getString(R.string.pageInfo, 1, 1));
        btnSkip = (Button) findViewById(R.id.btnSkip);
        btnSkip.setOnClickListener(this);

        totalPage = 50;

        grvThumbs = (GridView) findViewById(R.id.grvThumbs);
        grvThumbs.setOnItemClickListener(this);
        grvThumbs.setOnScrollListener(this);
        if (imageUrls == null) {
            imageUrls = new ArrayList<ImageDataBean>();
        }
        adapter = new MainImagesAdapter(this, handler, imageUrls);
        grvThumbs.setAdapter(adapter);
        // 抖动箭头
        imvArrow = (ImageView) findViewById(R.id.imvArrow);
        imvArrow.setVisibility(View.GONE);
        shake = AnimationUtils.loadAnimation(this, R.anim.shake_up_down);
        // 底部loading
        rllLoading = (RelativeLayout) findViewById(R.id.rllLoading);

        LoadDataFromNet(page = 1);
        preSetting = getSharedPreferences(Const.SHARED_PREFERENCES_MESSAGE, Context.MODE_PRIVATE);
        if (preSetting.getBoolean(Const.SHP_MAIN, true)) {
            imvMainDesc = (ImageView) findViewById(R.id.imvMainDesc);
            imvMainDesc.setVisibility(View.VISIBLE);
            imvMainDesc.setOnClickListener(this);
        }
    }

    @Override
    public void inflateByJson(int type, String jsonStr, int what) {
        LogOut.out(this, "jsonData[" + jsonStr + "]");
        JSONObject object = null;
        JSONArray array = null;
        Message msg = null;
        // 网络数据请求锁
        lock = false;
        try {
            if (type == JsonInflater.TYPE_OK) {
                object = new JSONObject(jsonStr);
                // object = new JSONObject(Tools.loadHttpData(ActZhengdian.this,
                // "data2"));
                String code = object.getString("status");
                if (what == Const.ACT$GETIMAGEDATA) {
                    if (code.equals("success")) {
                        page++;
                        array = object.getJSONArray("result");
                        dataProcessing(array, imageUrls);
                        handler.sendEmptyMessage(Const.ACT$GETIMAGEDATA_SUCESS);
                        if (array.length() < Const.COLUM_COUNT) { // 小于18张，认为到底了
                            lastPage = true;
                        }
                    }
                } else if (what == Const.ACT_UPGRADE) {
                    if (code.equals("success")) {
                        // 获取的versioncode
                        int remoteVersionCode = object.getInt("versionCode");
                        // 编译的versioncode
                        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                        int buildVersionCode = pinfo.versionCode;
                        if (remoteVersionCode > buildVersionCode) {
                            msg = handler.obtainMessage();
                            msg.what = what;
                            msg.obj = object.getString("url");
                            handler.sendMessage(msg);
                        }
                    }
                }
            } else if (type == JsonInflater.TYPE_NETWORK_ERROR) {
                handler.sendEmptyMessage(Const.CHECK_NETWORK);
            } else if (type == JsonInflater.TYPE_SERVER_ERROR) {
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                msg = handler.obtainMessage();
                msg.what = Const.SHOW_TOAST;
                msg.obj = getString(R.string.serverError);
                handler.sendMessage(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dataProcessing(JSONArray array, ArrayList<ImageDataBean> listBeans) {
        int size = array.length();
        JSONObject tmpObject = null;
        ImageDataBean tmpBean = null;
        for (int i = 0; i < size; i++) {
            tmpBean = new ImageDataBean();
            try {
                tmpObject = array.getJSONObject(i);
                tmpBean.thumbUrl = tmpObject.getString("thumbs");
                tmpBean.imageUrl = tmpObject.getString("image");
                listBeans.add(tmpBean);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onClick(View v) {
        if (v instanceof Button) {
            if (v == btnManager) {
                MobclickAgent.onEvent(ActZhengdian.this, "click_buttom", "管理按钮");
                Tools.switchActivity(this, ActManager.class, null);
            } else if (v == btnMore) {
                MobclickAgent.onEvent(ActZhengdian.this, "click_buttom", "更多按钮");
                Tools.switchActivity(this, ActMore.class, null);
            } else if (v == btnSkip) {
                String strPage = edtInputPage.getText().toString();
                if (strPage == null || strPage.equals("")) {
                    Tools.showShortToast(this, getString(R.string.inputEmpty));
                } else {
                    int page = Integer.parseInt(strPage);
                    if (page > totalPage) {
                        Tools.showShortToast(this, "只有50页，请重新输入");
                    } else {
                        this.page = page;
                        LoadDataFromNet(page);
                    }
                }
            }
        } else if (v instanceof ImageView) {
            if (v == imvMainDesc) {
                imvMainDesc.setClickable(false);
                imvMainDesc.setVisibility(View.GONE);
                Editor editor = preSetting.edit();
                editor.putBoolean(Const.SHP_MAIN, false);
                editor.commit();
            }
            // else {
            // int pos = (Integer) v.getTag();
            // if (imageUrls != null && imageUrls.size() > 0) {
            // Bundle bundle = new Bundle();
            // String selString = imageUrls.get(pos).imageUrl;
            // bundle.putString(Const.BUNDLE_IMAGEURL, selString);
            // Tools.switchActivity(ActZhengdian.this, ActImageDetail.class,
            // bundle);
            // // 统计浏览的图片
            // MobclickAgent.onEvent(ActZhengdian.this, "click_see_image",
            // selString.substring(selString.lastIndexOf("/")));
            // }
            // }
            // Toast.makeText(ActZhengdian.this, pos + "",
            // Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showQuitDialog();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showQuitDialog() {
        quitDialog = DialogUtil.showQuitDialog(this, handler);
    }

    /** 创建快捷方式 */
    private void createShortcut() {
        String status = spre.getString(Const.SHARED_SHORTCUT, ActZhengdian.SHORTCUT_NOASK);
        if (ActZhengdian.SHORTCUT_NOASK.equals(status)) {
            SharedPreferences.Editor editor = spre.edit();
            editor.putString(Const.SHARED_SHORTCUT, ActZhengdian.SHORTCUT_AGREE);
            editor.commit();
            addShortcut(this, getPackageName());

        }

    }

    private boolean addShortcut(Context context, String pkgName) {
        // 快捷方式名称
        String title = "unknown";
        // MainActivity完整名
        String mainAct = null;
        // 应用图标标识
        int iconIdentifier = 0;
        // 根据包名寻找MainActivity
        PackageManager pkgMag = context.getPackageManager();
        Intent queryIntent = new Intent(Intent.ACTION_MAIN, null);
        queryIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> list = pkgMag.queryIntentActivities(queryIntent, PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(pkgName)) {
                title = info.loadLabel(pkgMag).toString();
                mainAct = info.activityInfo.name;
                iconIdentifier = info.activityInfo.applicationInfo.icon;
                break;
            }
        }
        if (mainAct == null) {
            // 没有启动类
            return false;
        }
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 快捷方式的名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
        // 不允许重复创建
        shortcut.putExtra("duplicate", false);
        ComponentName comp = new ComponentName(pkgName, mainAct);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
        // 快捷方式的图标
        Context pkgContext = null;
        if (context.getPackageName().equals(pkgName)) {
            pkgContext = context;
        } else {
            // 创建第三方应用的上下文环境，为的是能够根据该应用的图标标识符寻找到图标文件。
            try {
                pkgContext = context.createPackageContext(pkgName, Context.CONTEXT_IGNORE_SECURITY
                        | Context.CONTEXT_INCLUDE_CODE);
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        if (pkgContext != null) {
            ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(pkgContext, iconIdentifier);
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
        }
        // 发送广播，让接收者创建快捷方式
        // 需权限<uses-permission
        // android:name="com.android.launcher.permission.INSTALL_SHORTCUT"
        // />
        context.sendBroadcast(shortcut);
        return true;

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (check) {
            check = false;
            LoadDataFromNet(page);
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        ImageManager.getManger().clearCache();
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                if (!lock) {
                    if (!lastPage) {
                        // 如果是已经缓存过的页面，自加一
                        if (page == bufferedPage) {
                            page++;
                        }
                        LoadDataFromNet(page);
                        lock = true;
                    } else {
                        Message msg = handler.obtainMessage();
                        msg.what = Const.SHOW_TOAST;
                        msg.obj = getString(R.string.lastPage);
                        handler.sendMessage(msg);
                        rllLoading.setVisibility(View.GONE);
                    }
                }
            }
        } else if (scrollState == OnScrollListener.SCROLL_STATE_FLING) {

        } else if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
            // imvArrow.setAnimation(null);
            // imvArrow.setVisibility(View.GONE);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
        // TODO Auto-generated method stub
        Bundle bundle = new Bundle();
        String selString = imageUrls.get(position).imageUrl;
        bundle.putString(Const.BUNDLE_IMAGEURL, selString);
        Tools.switchActivity(ActZhengdian.this, ActImageDetail.class, bundle);
        // 统计浏览的图片
        MobclickAgent.onEvent(ActZhengdian.this, "click_see_image", selString.substring(selString.lastIndexOf("/")));
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //  保存缓存页码
        if (Tools.hasNetwork(this) && imageUrls != null && imageUrls.size() >= 18) {
            Editor editor = spre.edit();
            // 减去预加载页数1
            page--;
            editor.putString(Const.SHARED_BUFFEREDPAGE, String.valueOf(page));
            editor.commit();
            // 把数据写入数据库
            int totalIndex = (page) * Const.COLUM_COUNT;
            int lastIndex = totalIndex - 1;
            ImageBufferDB tmpBufferDB = null;
            helper.openWritableDatabase();
            helper.clearAllRecord();
            for (int i = totalIndex - Const.COLUM_COUNT; i <= lastIndex; i++) {
                tmpBufferDB = new ImageBufferDB();
                tmpBufferDB.image = imageUrls.get(i).imageUrl;
                tmpBufferDB.thumbs = imageUrls.get(i).thumbUrl;
                tmpBufferDB.page = String.valueOf(page);
                helper.insertItem(tmpBufferDB.conver3ContentValues());
            }
            helper.close();
        }
    }

}
